package site.marqstree.latte.ui.refresh;

import android.view.LayoutInflater;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import java.util.ArrayList;
import java.util.List;

import site.marqstree.latte.core.app.Latte;
import site.marqstree.latte.core.net.RestClient;
import site.marqstree.latte.core.net.callback.IError;
import site.marqstree.latte.core.net.callback.IFailure;
import site.marqstree.latte.core.net.callback.ISuccess;
import site.marqstree.latte.ui.R;
import site.marqstree.latte.ui.recycler.CustomLoadMoreView;
import site.marqstree.latte.ui.recycler.DataConverter;
import site.marqstree.latte.ui.recycler.MultipleItemEntity;
import site.marqstree.latte.ui.recycler.MultipleRecyclerAdapter;

/*
 * 项目名: EleCommerce
 * 包名: site.marqstree.latte.ui.refresh
 * 文件名: RefreshHandler
 * 创建者: marqstree
 * 创建时间: 2020/1/22 9:12
 * 描述: 下拉刷新控件事件处理器
 */
public class RefreshHandler implements
        SwipeRefreshLayout.OnRefreshListener,
        OnLoadMoreListener {

    //下拉刷新控件
    private final SwipeRefreshLayout REFRESH_LAYOUT;
    //计算总行数
    private final PagingBean BEAN = new PagingBean();
    //RecyclerView列表控件
    private final RecyclerView RECYCLERVIEW;
    //RecyclerView列表适配器
    private MultipleRecyclerAdapter mAdapter = new MultipleRecyclerAdapter();
    //json转bean工具
    private final DataConverter CONVERTER;
    //请求列表数据地址
    private String mUrl;

    public static RefreshHandler create(SwipeRefreshLayout swipeRefreshLayout,
                                        RecyclerView recyclerView,
                                        DataConverter converter) {
        return new RefreshHandler(swipeRefreshLayout, recyclerView, converter);
    }

    private RefreshHandler(SwipeRefreshLayout swipeRefreshLayout,
                           RecyclerView recyclerView,
                           DataConverter converter) {
        //接收下拉刷新控件
        this.REFRESH_LAYOUT = swipeRefreshLayout;
        this.RECYCLERVIEW = recyclerView;
        this.CONVERTER = converter;
        //绑定下拉事件
        REFRESH_LAYOUT.setOnRefreshListener(this);

        // 2)设置页脚视图
        mAdapter.getLoadMoreModule().setLoadMoreView(new CustomLoadMoreView());
        // 开启上拉加载下一页数据（默认为true）
        //关闭时，需点击页脚，才能加载下一页数据
        mAdapter.getLoadMoreModule().setAutoLoadMore(true);
        //设置上拉或点击页脚监听
        mAdapter.getLoadMoreModule().setOnLoadMoreListener(this);
        //当自动加载开启，同时数据不满一屏时，不允许继续执行自动加载更多(默认为true)
        mAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);

        //绑定适配器
        RECYCLERVIEW.setAdapter(mAdapter);
    }

    //下拉刷新事件
    @Override
    public void onRefresh() {
        //开启无限转圈动画
        REFRESH_LAYOUT.setRefreshing(true);
        //防止下拉刷新的时候还可以上拉加载
        mAdapter.getLoadMoreModule().setEnableLoadMore(false);

        //重新获取第一页数据
        BEAN.resetFirstPageIndex();
        getDataByPage(mUrl,1);

        //0.3秒后关闭无限转圈动画
        Latte.getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //关闭无限转圈动画
                REFRESH_LAYOUT.setRefreshing(false);
            }
        }, 300);
    }

    //请求下一页数据
    public void getDataByPage(String url, final int pageIndex){
        //记录请求url
        mUrl = url;
        //耗时操作，显示等待页面
        mAdapter.setEmptyView(R.layout.loading_view);
        //请求列表数据
        RestClient.builder()
                .url(url)
                .params("index",pageIndex)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        final JSONObject object = JSON.parseObject(response);
                        int totalItemCount = object.getInteger("total");
                        int pageItemCount = object.getInteger("page_size");

                        //生成View Model数组
                        CONVERTER.setJsonData(response);
                        ArrayList<MultipleItemEntity> list = CONVERTER.convert();

                        //显示页脚布局
                        mAdapter.getLoadMoreModule().setEnableLoadMore(true);

                        //如果是加载的第一页数据，用setNew
                        if(pageIndex==1) {
                            if(pageItemCount>0) {
                                mAdapter.setNewData(list);
                                //重置页码、Item数
                                BEAN.resetFirstPageIndex();
                                //累加页码、行数
                                BEAN.addItem(pageItemCount);
                            }
                        }else {
                            if(pageItemCount>0) {
                                //不是第一页，则用add追加数据
                                mAdapter.addData(list);
                                //累加页码、Item数
                                BEAN.addItem(pageItemCount);
                            }
                        }

                        //如果请求不到新数据,页脚显示“全部加载结束，没有数据”的View
                        if ( BEAN.getItemCount() >= totalItemCount ) {
                            mAdapter.getLoadMoreModule().loadMoreEnd();
                        } else {
                            //页脚显示当前一页加载完成
                            mAdapter.getLoadMoreModule().loadMoreComplete();
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        //如果请求第一页失败，表格中显示报错View
                        if (pageIndex == 1) {
                            //清空列表数据缓存
                            mAdapter.setNewData(null);
                            //显示错误视图
                            mAdapter.setEmptyView(getErrorView());
                        }
                        //非首页数据加载失败，在页脚显示报错View
                        else{
                            //结束下拉刷新动画
                            REFRESH_LAYOUT.setRefreshing(false);
                            //显示页脚布局
                            mAdapter.getLoadMoreModule().setEnableLoadMore(true);
                            //显示加载错误页脚布局
                            mAdapter.getLoadMoreModule().loadMoreFail();
                        }
                    }
                })
                .failure(new IFailure() {
                    @Override
                    public void onFailure() {
                        //如果请求第一页失败，表格中显示报错View
                        if (pageIndex == 1) {
                            //清空列表数据缓存
                            mAdapter.setNewData(null);
                            //显示错误视图
                            mAdapter.setEmptyView(getErrorView());
                        }
                        //非首页数据加载失败，在页脚显示报错View
                        else {
                            //结束下拉刷新动画
                            REFRESH_LAYOUT.setRefreshing(false);
                            //显示页脚布局
                            mAdapter.getLoadMoreModule().setEnableLoadMore(true);
                            //显示加载错误页脚布局
                            mAdapter.getLoadMoreModule().loadMoreFail();
                        }
                    }
                })
                .build()
                .get();
    }

    //下拉加载数据事件
    @Override
    public void onLoadMore() {
        //请求下一页数据
        getDataByPage(mUrl,BEAN.getLastPageIndex()+1);
    }

    //获取空数据视图
    private View getEmptyDataView() {
        LayoutInflater inflater = LayoutInflater.from(Latte.getApplicationContext());
        View notDataView = inflater.inflate(R.layout.empty_view, RECYCLERVIEW, false);
        notDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        return notDataView;
    }

    //获取错误视图
    private View getErrorView() {
        LayoutInflater inflater = LayoutInflater.from(Latte.getApplicationContext());
        View errorView = inflater.inflate(R.layout.empty_view, RECYCLERVIEW, false);
        errorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        return errorView;
    }

    //获取适配器
    public MultipleRecyclerAdapter getAdapter(){
        return mAdapter;
    }

}